import sql from '@/utils/sqlLite.js'
import {
	setObjSql,
	obj2str_sql
} from '@/utils/index.js'
export const database = {
	name: 'zs123456', //数据库
	path: '_doc/zs123456.db', //数据库地址
}
// 数据表名称
export const user = 'user'
// 用户数据表
/*
id id
name 名称
phone 手机
userImg 头像
rentNum 租赁次数
userTotal 用户积分
lastTimeRent 上次租赁时间
grade 会员等级
*/
// 创建数据表
export const cratetable = async () => {
	let sqltxt = [
		`create table  ${user}("id" VARCHAR(64),"name" VARCHAR(64),"phone" VARCHAR(24),"grade" VARCHAR(1),"userImg" VARCHAR(128),"rentNum" VARCHAR(32),"userTotal" VARCHAR(100),"lastTimeRent" VARCHAR(64))`
	];
	let res = await sql.executeSQL(database, sqltxt);
	console.log(res);
}

// 添加用户
export const addUser = async (pushData) => {
	// 数据库中id 存在 修改 ，不存在 新增
	let sqltxt = `select *from ${user} where id = '${pushData.id}'`;
	let res = await sql.selectSQL(database, sqltxt);
	console.log(res);
	if (res.code == 0 && res.data.length == 0) { //数据库中没有数据 新增

		let condition = Object.keys(pushData).join(',')
		// let data = `'${pushData.id}','${pushData.name}','${pushData.phone}','${pushData.userImg}'`
		let data = setObjSql(pushData)
		let sqltxt = `INSERT  INTO ${user} (${condition}) VALUES(${data})`
		return await sql.executeSQL(database, sqltxt);

	} else { //存在 ，更改

		// let data = `name='${pushData.name}',phone='${pushData.phone}',userImg='${pushData.userImg}',rentNum='${pushData.rentNum}',userTotal='${pushData.userTotal}',lastTimeRent='${pushData.lastTimeRent}'`
		let data = obj2str_sql(pushData)

		let sqltxt = `update  ${user} set ${data} where id = '${pushData.id}'`

		return await sql.executeSQL(database, sqltxt);

	}
}

// 删除用户 id 
export const removeUser = async (id) => {
	let sqltxt = [
		`delete from  ${user}  where id = '${id}'`
	];
	return sql.executeSQL(database, sqltxt);

}
// 获取全部的用户
export const getUser = async () => {
	let sqltxt = `select * from ${user}`;
	return await this.$sql.selectSQL(database, sqltxt);

}